/**
 * Copyright 2007 Luke Pillow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.orsomethinglikethat.flex.filemaker
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import com.orsomethinglikethat.flex.filemaker.request.FileMakerResultEvent;
	
	public class FileMakerResultHandler extends EventDispatcher
	{
		private var fieldMeta:XMLList;
		
		private var records:Array = new Array();
		
		public function FileMakerResultHandler()
		{
			super();
		}
		
		public function parse( event:Event ):void
		{
			this.parseXML( new XML( event.target.data ) );
		}
		
		private function parseXML( xml:XML ):void
		{
			for each ( var element:XML in xml.elements() )
			{
				if( element.localName() == "METADATA" )
				{
					this.fieldMeta = element.children();
				}
				else if( element.localName() == "RESULTSET" )
				{
					for each ( var row:XML in element.children() )
					{
						this.records.push( new Record( row, this.fieldMeta ) );
					}				
				}
			}	
			
			this.dispatchEvent( new FileMakerResultEvent( FileMakerResultEvent.COMPLETE, this.records ) );
		}
		
	}
}